package com.xuecheng.media.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.*;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mapper.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-08
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private VodTemplate vodTemplate;
    // 获取上传凭证
    @Override
    public ResponseResult<VodUploadVo> vodToken(VodUploadDto dto) {
        // 1.参数校验
        if (StrUtil.isEmpty(dto.getFileName())
                || StrUtil.isEmpty(dto.getTitle())) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        try {
            // 2.获取上传凭证
            CreateUploadVideoResponse response = vodTemplate.createUploadVideo(dto.getTitle(), dto.getFileName());
            // 3.转vo
            VodUploadVo vo = BeanHelper.copyProperties(response, VodUploadVo.class);
            // 4.返回vo
            return ResponseResult.okResult(vo);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.ALIYUNERROR);
        }
    }

    // 刷新上传凭证
    @Override
    public ResponseResult<VodUploadVo> refreshVodToken(String videoId) {
        // 1.参数校验
        if (StrUtil.isEmpty(videoId)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        try {
            // 2.刷新token
            RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);
            // 3.转vo
            VodUploadVo vo = BeanHelper.copyProperties(response, VodUploadVo.class);
            // 4.返回vo
            return ResponseResult.okResult(vo);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.ALIYUNERROR);
        }
    }

    // 保存媒资
    @Override
    public ResponseResult saveMedia(MediaDto dto) throws Exception {
        // 1.校验参数
        if (StrUtil.isEmpty(dto.getFilename()) ||
                StrUtil.isEmpty(dto.getFileId())) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        // 2.dto转实体
        Media media = BeanHelper.copyProperties(dto, Media.class);
        // 3.根据视频id获取播放地址和时长
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(media.getFileId());
        // 3-1 时长   91.1
        String duration = response.getPlayInfoList().get(0).getDuration();
        // 3-2 地址
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        // 4.补充media信息
        media.setUrl(playURL); // 播放地址
        // 视频时长   91.1 ->   01:31
        Float f = Float.parseFloat(duration);
        LocalTime localTime = LocalTime.MIN.plusMinutes(f.longValue());
        media.setTimelength(localTime.toString());

        media.setUsername(AuthInfoHolder.getUserId().toString()); // 上传人
        media.setCreateDate(new Date()); // 上传时间
        media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS); // 审核状态
        // 5.保存数据库
        this.save(media);
        // 6.返回ok
        return ResponseResult.okResult();
    }

    // 媒资分页查询
    @Override
    public ResponseResult<MediaVo> findByPage(PageRequest pageRequest, MediaQueryDto dto) {
        // 1.构建分页
        Page<Media> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        // 2.条件分页查询
        page = this.lambdaQuery()
                .like(StrUtil.isNotEmpty(dto.getFilename()), Media::getFilename, dto.getFilename())
                .eq(StrUtil.isNotEmpty(dto.getType()), Media::getType, dto.getType())
                .eq(StrUtil.isNotEmpty(dto.getAuditStatus()), Media::getAuditStatus, dto.getAuditStatus())
                .page(page);

        // 3.media转vo
        List<Media> mediaList = page.getRecords();
        List<MediaVo> voList = BeanHelper.copyWithCollection(mediaList, MediaVo.class);
        // 4.返回分页
        return PageResponseResult.okResult(page.getTotal(),voList);
    }

    // 媒资预览
    @Override
    public ResponseResult<String> preview(Long mediaId) throws Exception{

        // 1.查询媒资对象
        Media media = this.getById(mediaId);
//        //查询数据库媒资地址
//        String url = media.getUrl();
//        String substring = url.substring(45, 55);
//        if ()
        // 2.根据视频id查询最新播放地址
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(media.getFileId());
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        // 3.返回播放地址
        return ResponseResult.okResult(playURL);
    }

    // 媒资删除
    @Override
    public ResponseResult deleteMedia(Long mediaId) throws Exception{
        // 1.查询媒资对象
        Media media = this.getById(mediaId);
        // 2.判断审核状态
        if (media.getAuditStatus().equals(MediaConstants.AUDIT_PASTED_STATUS)) {
            // 审核通过不让删
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        // 3.删除阿里云
        vodTemplate.deleteVideo(media.getFileId());
        // 4.删除数据库
        this.removeById(mediaId);
        // 5.返回ok
        return ResponseResult.okResult();
    }

    //媒资审核
    @Override
    public ResponseResult auditMedia(MediaAuditDto mediaAuditDto) {
        //1.先查询判断状态
        Media media = this.getById(mediaAuditDto.getId());
        String auditStatus = media.getAuditStatus();
        //只能审核未审核的
        if (!StrUtil.equals(auditStatus, MediaConstants.AUDIT_UNPAST_STATUS)) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        //2.状态审核 提交
        media.setAuditStatus(mediaAuditDto.getAuditStatus());
        media.setAuditMind(mediaAuditDto.getAuditMind());
        this.updateById(media);
        return ResponseResult.okResult();
    }

    // 课程详情页查询媒资播放地址
    @Override
    public ResponseResult<ResourceVo> mediaUrl(Long mediaId) throws Exception {
        // 1.查询媒资对象
        Media media = this.getById(mediaId);
        // 2.根据视频id查询最新播放地址
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(media.getFileId());
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        // 3.封装vo
        ResourceVo vo = new ResourceVo();
        vo.setPlayUrl(playURL);
        // 4.返回vo
        return ResponseResult.okResult(vo);
    }
}
